//
//  TieZiInfoViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/8.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "TieZiInfoViewController.h"
#import "TieZiInfoTableViewCell.h"
//#import "TieZiInfoModel.h"

@interface TieZiInfoViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, weak)UIImageView * iconImageView;
@property (nonatomic, weak)UILabel * nameLabel;
@property (nonatomic, weak)UILabel * timeLabel;
@property (nonatomic, weak)UIImageView * backImageView;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UITextField * sayTextFiled;
@property (nonatomic, weak)UIButton * sureButton;
@property (nonatomic, strong)NSArray <NSDictionary *> * modelListArray;

@end

@implementation TieZiInfoViewController


-(void)setModelListArray:(NSArray<NSDictionary *> *)modelListArray{
    
    _modelListArray = modelListArray;
    
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{

    NSString * str = [NSString stringWithFormat:@"index/Common/noteDetail?note_id=%@",self.ID];
    
    [[NetworkTool sharedTools] GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"=========%@",responseObject);
        int status = [responseObject[@"status"] intValue];
        
        if (status == 200) {
            
            NSDictionary * data = responseObject[@"data"];
            
            NSURL * iconUrl = [NSURL URLWithString:data[@"headimg"]];
            [self.iconImageView sd_setImageWithURL:iconUrl];
            self.titleLabel.text = data[@"title"];
            self.nameLabel.text = data[@"username"];
            // timeStampString 是服务器返回的13位时间戳
            NSString *timeStampString  = data[@"ctime"];
            
            // iOS 生成的时间戳是10位
            NSTimeInterval interval    =[timeStampString doubleValue];
            NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSString *dateString       = [formatter stringFromDate: date];
            self.timeLabel.text = dateString;
            
            NSArray * arr = data[@"images"];
            NSURL * backUrl = [NSURL URLWithString:arr.firstObject];
            [self.backImageView sd_setImageWithURL:backUrl];
            
            self.modelListArray = data[@"comments"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error======%@",error);
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = WHITE_COLOR;
    
    [self setupNav];
    [self setupUI];
}


- (void)setupNav{
    
    self.title = @"详情";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"1返回"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setupUI{
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.textColor = BLACK_COLOR;
    titleLabel.font = [UIFont systemFontOfSize:17 * SCREENH6];
    titleLabel.text = @"阿斯蒂芬哪怕";
    
    self.titleLabel = titleLabel;
    
    [self.view addSubview:self.titleLabel];
    
    
    UIImageView * iconImageView = [UIImageView new];
    
    //  把图片设置成圆形
    iconImageView.layer.cornerRadius = 18;//裁成圆角
    iconImageView.layer.masksToBounds = YES;//隐藏裁剪掉的部分
    iconImageView.backgroundColor = [UIColor grayColor];
    //    iconImageView.image = ImageNamed(@"头像7");
    
    self.iconImageView = iconImageView;
    
    [self.view addSubview:self.iconImageView];
    
    
    UILabel * nameLabel = [UILabel new];
    
    nameLabel.textColor = BLACK_COLOR;
    nameLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    nameLabel.text = @"阿斯蒂芬哪怕";
    
    self.nameLabel = nameLabel;
    
    [self.view addSubview:self.nameLabel];
    
    
    UILabel * timeLabel = [UILabel new];
    
    timeLabel.textColor = [UIColor lightGrayColor];
    timeLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    timeLabel.text = @"2分钟前";
    
    self.timeLabel = timeLabel;
    
    [self.view addSubview:self.timeLabel];
    
    UIImageView * backImageView = [UIImageView new];
    
    backImageView.image = ImageNamed(@"");
    backImageView.backgroundColor = [UIColor lightGrayColor];
    
    self.backImageView = backImageView;
    
    [self.view addSubview:self.backImageView];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe6e6e6);
    
    self.lineView = lineView;
    
    [self.view addSubview:self.lineView];
 
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 335 * SCREENH6, SCREEN_WIDTH, SCREENH_HEIGHT - 440 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.rowHeight = 122 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[TieZiInfoTableViewCell class] forCellReuseIdentifier:@"TieziInfoListCell"];
    
    [self.view addSubview:self.tableView];
    
    
    UITextField * sayTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 5 * SCREENH6, 260 * SCREENH6, 30 * SCREENH6)];
    
    sayTextFiled.borderStyle = UITextBorderStyleLine;
    sayTextFiled.backgroundColor = [UIColor whiteColor];
    //设置光标颜色
    sayTextFiled.tintColor = [UIColor whiteColor];
    sayTextFiled.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor lightGrayColor];
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    sayTextFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"来了就说点啥吧！" attributes:attrs];
    sayTextFiled.textColor = [UIColor blackColor];
    sayTextFiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    sayTextFiled.returnKeyType = UIReturnKeyDone;
//    sayTextFiled.delegate = self;
    
    self.sayTextFiled = sayTextFiled;
    
    [self.view addSubview:self.sayTextFiled];
    
    
    UIButton * sureButton = [UIButton new];
    
    [sureButton setTitle:@"确认" forState:UIControlStateNormal];
    [sureButton setTitleColor:MAINCOLOR forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
    sureButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.sureButton = sureButton;
    
    [self.view addSubview:self.sureButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(7 * SCREENH6);
    }];
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(15 * SCREENH6);
        make.height.width.mas_equalTo(36 * SCREENH6);
    }];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView.mas_trailing).offset(15 * SCREENH6);
        make.top.mas_equalTo(self.iconImageView);
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.nameLabel);
        make.top.mas_equalTo(self.nameLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.top.mas_equalTo(self.iconImageView.mas_bottom).offset(20 * SCREENH6);
        make.height.mas_equalTo(195 * SCREENH6);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.backImageView.mas_bottom).offset(40 * SCREENH6);
    }];
    
    [self.sayTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30 * SCREENH6);
        make.bottom.mas_equalTo(self.view).offset(-5 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.width.mas_equalTo(310 * SCREENH6);
    }];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view);
        make.leading.mas_equalTo(self.sayTextFiled.mas_trailing);
        make.centerY.height.mas_equalTo(self.sayTextFiled);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSLog(@"++++++=%lu",(unsigned long)self.modelListArray.count);
    return self.modelListArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    TieZiInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TieziInfoListCell" forIndexPath:indexPath];
    
    cell.dict = self.modelListArray[indexPath.row];
    
    return cell;
    
}


- (void)clickSureButton{
    
    [self.sayTextFiled resignFirstResponder];
    
    NSString * user_id = DEF_GET_OBJECT(@"user_id");
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dict = @{@"user_id":user_id,@"note_id":self.ID,@"content":self.sayTextFiled.text,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/index/COmmon/comment" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        int status = [responseObject[@"status"] intValue];
        
        if (status == 200) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，评论成功！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
